# -*- coding: utf-8 -*-

from ..models import StructureNode
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse

class StructureNodeAdminForm(forms.ModelForm):

    POSITION_FIRST_CHILD = 'first-child'
    POSITION_LAST_CHILD = 'last-child'
    POSITION_LEFT = 'left'
    POSITION_RIGHT = 'right'

    POSITION_CHOICES = (
        ('', '---'),
        (POSITION_FIRST_CHILD, _(u'перывый потомок')),
        (POSITION_LAST_CHILD, _(u'последний потомок')),
        (POSITION_LEFT, _(u'сосед сверху')),
        (POSITION_RIGHT, _(u'сосед снизу')),
        )
    
    target = forms.ChoiceField(label=_(u'цель'), required=False)
    position = forms.ChoiceField(label=_(u'положение'), 
                                 choices=POSITION_CHOICES, required=False)

    class Meta:
        model = StructureNode

    def __init__(self, *args, **kwargs):
        super(StructureNodeAdminForm, self).__init__(*args, **kwargs)
        
        if self.instance.pk is None or self.instance.level > 0:
            opts = self.instance._meta
            if self.instance.pk is None:
                valid_targets = StructureNode.objects.all()
            else:
                if self.instance.parent:
                    self.fields['target'].initial = self.instance.parent.pk
                valid_targets = self.instance._tree_manager.exclude(**{
                    opts.tree_id_attr: getattr(self.instance, opts.tree_id_attr),
                    '%s__gte' % opts.left_attr: getattr(self.instance, opts.left_attr),
                    '%s__lte' % opts.right_attr: getattr(self.instance, opts.right_attr),
                    })
            choices = [(
                target.pk, '%s %s (%s)' % (
                    '---' * getattr(target, opts.level_attr), target.get_menu(), target.path)
                ) for target in valid_targets]
            choices.insert(0, (0, '-'))
            self.fields['target'].choices = choices

    def clean_target(self):
        if StructureNode.objects.count() == 0:
            return 0

        target = self.cleaned_data['target'] or None

        if self.instance.pk is None and target == '0':
            raise forms.ValidationError(_(u'Укажите цель'))

        if target is not None:
            return StructureNode.objects.get(pk=target)

        return None

    def clean_position(self):
        if StructureNode.objects.count() == 0:
            return 0

        position = self.cleaned_data['position']
        if self.instance.pk is None and not position:
            raise forms.ValidationError(_(u'Укажите позицию'))
        return position

    def save(self, *args, **kwargs):
        if StructureNode.objects.count() != 0:
            target, position = self.cleaned_data['target'], self.cleaned_data['position']
            instance = super(StructureNodeAdminForm, self).save(commit=False)
            if instance.pk and position:
                instance.move_to(target, position)
            elif instance.pk is None:
                instance = StructureNode.objects.insert_node(instance, target, position)
            instance.save()
        else:
            instance = super(StructureNodeAdminForm, self).save(*args, **kwargs)
        return instance
#EOF